package org.nf.box.service.impl;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.box.domain.Comment;
import org.nf.box.domain.Like;
import org.nf.box.domain.Post;
import org.nf.box.mapper.CommentMapper;
import org.nf.box.mapper.LikeMapper;
import org.nf.box.mapper.PostMapper;
import org.nf.box.service.FollowService;
import org.nf.box.service.LikeService;
import org.nf.box.service.PostService;
import org.nf.box.web.vo.PostVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;

/**
 * @Author lzp
 * @Date 2024-12-10
 * 帖子业务
 */
@Service("postService")
@RequiredArgsConstructor
@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
public class PostServiceImpl implements PostService {

    private final PostMapper postMapper;
    private final MinioClient minioClient;
    private final CommentMapper commentMapper;
    private final LikeMapper likeMapper;
    private final FollowService followService;
    private final LikeService likeService;

//    @Override
//    public List<PostVO> getPosts(String status,Integer userId) {
//        List<PostVO> posts = postMapper.getPosts(status);
//        for (PostVO post : posts) {
//            //设置分享数
//            post.setShare(0);
//            //设置图片数组 （多个图片名,用逗号分割成一个数组）
//            post.setImgList(post.getImage().split(","));
//            //设置用户对帖子作者关注状态
//            Integer follow = followService.isAttention(userId, post.getUserId());
//            post.setIsAttention(follow);
//            //设置用户对帖子点赞状态
//            Integer like = likeService.isLike(userId, post.getPostId());
//            post.setIsLink(like);
//            //设置点赞数
//            Integer likeCount = postMapper.getLikeCount(post.getPostId());
//            post.setLikeCount(likeCount);
//            //设置总评论数
//            Integer totalComments = commentMapper.getTotalComment(post.getPostId());
//            post.setCommentCount(totalComments);
//        }
//        return posts;
//    }

    /**
     * 获取所有帖子
     * @param status 帖子状态
     * @param userId 用户id
     * @return
     */
    @Override
    public List<PostVO> getPosts(String status,Integer userId) {
        List<PostVO> posts = postMapper.getPosts(status);
        for (PostVO post : posts) {
            //设置分享数
            post.setShare(0);
            //设置图片数组 （多个图片名,用逗号分割成一个数组）
            post.setImgList(post.getImage().split(","));
            //设置用户对帖子作者关注状态
            Integer follow = followService.isAttention(userId, post.getUserId());
            post.setIsAttention(follow);
            //设置用户对帖子点赞状态
            Integer like = likeService.isLike(userId, post.getPostId());
            post.setIsLink(like);
        }
        return posts;
    }

    /**
     * 获取视频帖子
     * @param status 帖子状态
     * @param userId 用户id
     * @return 帖子列表
     */
    @Override
    public List<PostVO> getVideo(String status, Integer userId) {
        List<PostVO> posts = postMapper.getVideo(status);
        for (PostVO post : posts) {
            //设置分享数
            post.setShare(0);
            //设置图片数组 （多个图片名,用逗号分割成一个数组）
            post.setImgList(post.getImage().split(","));
            //设置用户对帖子作者关注状态
            Integer follow = followService.isAttention(userId, post.getUserId());
            post.setIsAttention(follow);
            //设置用户对帖子点赞状态
            Integer like = likeService.isLike(userId, post.getPostId());
            post.setIsLink(like);
        }
        return posts;
    }

    /**
     * 获取推荐帖子
     * @param status 帖子状态
     * @param userId 用户id
     * @return 帖子列表
     */
    @Override
    public List<PostVO> getRecommend(String status, Integer userId) {
        List<PostVO> posts = postMapper.getRecommend(status);
        for (PostVO post : posts) {
            //设置分享数
            post.setShare(0);
            //设置图片数组 （多个图片名,用逗号分割成一个数组）
            post.setImgList(post.getImage().split(","));
            //设置用户对帖子作者关注状态
            Integer follow = followService.isAttention(userId, post.getUserId());
            post.setIsAttention(follow);
            //设置用户对帖子点赞状态
            Integer like = likeService.isLike(userId, post.getPostId());
            post.setIsLink(like);
        }
        return posts;
    }


    /**
     * 获取帖子详情
     * @param postId 帖子id
     * @param userId 用户id
     * @return
     */
    @Override
    public PostVO postDetails(Integer postId,Integer userId) {
        PostVO post = postMapper.postDetails(postId);
        post.setShare(0);
        post.setImgList(post.getImage().split(","));
        Integer follow = followService.isAttention(userId, post.getUserId());
        post.setIsAttention(follow);
        Integer like = likeService.isLike(userId, post.getPostId());
        post.setIsLink(like);
        return post;
    }

    @Override
    public void createPost(Post post, String prefix, MultipartFile[] files) {
        Post p = new Post();
        p.setUserId(post.getUserId());
        p.setTitle(post.getTitle());
        p.setContent(post.getContent());
        p.setImage(post.getImage());
        p.setStatus(post.getStatus());
        p.setUploadType(post.getUploadType());
        //添加
        postMapper.addPost(post);
        //文件上传
        upload(prefix,files);
    }


    /**
     * 文件上传
     * @param prefix
     * @param files
     */
    @Override
    public void upload(String prefix,MultipartFile[] files) {
        for (MultipartFile file : files) {
            try {
                String fileName = file.getOriginalFilename();
                InputStream inputStream = file.getInputStream();
                minioClient.putObject(
                        PutObjectArgs.builder().bucket("myapp")
                                .object(prefix + "/" + fileName)
                                .stream(inputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Override
    public void updatePost(Post post, String prefix, MultipartFile[] files) {
        Post p = new Post();
        //p.setUserId(post.getUserId());
        p.setPostId(post.getPostId());
        p.setTitle(post.getTitle());
        p.setContent(post.getContent());
        p.setImage(post.getImage());
        p.setStatus(post.getStatus());
        postMapper.updatePost(p);
        //文件上传
        upload(prefix,files);
    }

    @Override
    public void deletePost(Integer postId) {
        //获取要删除贴子的信息
        Post post = postMapper.getPostById(postId);
        //如果帖子不为空
        if (post != null){
            postMapper.deletePost(postId);
            //拿到文件名称
            String image = post.getImage();
            //可能有多个文件名称 通过逗号把它们分割成一个数组
            String[] images = image.split(",");
            //调用移除文件方法
            remove(images);
        }
    }

    @Override
    public void remove(String[] images) {
        //循环移除
        for (String image : images) {
            try {
                minioClient.removeObject(
                        RemoveObjectArgs.builder()
                                //桶的名称
                                .bucket("myapp")
                                //路径 + 文件名
                                .object("images/"+image)
                                .build());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
